package qos.estimator.jdbc;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;

import qos.estimator.statistics.SystemStatisticsCollector;

public class QoSConnectionSPI {
	
	private ServerSocket serverSocket;
	private SystemStatisticsCollector statisticsCollector;
	private AtomicInteger numberOfConcurrentTransactions = new AtomicInteger(0);
	
	/*
	 * open a socket and listen to a specified port.
	 * when an SQL statement is received: 
	 * 		1) identify the SQL statement
	 * 		2) read server statistics
	 * 		3) use all as inputs for the estimator
	 * 		4) execute the statement and monitor the execution time
	 * 		5) update the knowledge base
	 */
	
	
	public void startServer(){
		statisticsCollector = new SystemStatisticsCollector();
		
		new Thread(new Runnable(){
			public void run() {
				statisticsCollector.startCollecting(true);
			}
			
		}).start();
		try {
			serverSocket = new ServerSocket(8888);
			while(true){
				Socket clientSocket = serverSocket.accept();
				new QoSConnectionHandlerThread(clientSocket, statisticsCollector, numberOfConcurrentTransactions).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		QoSConnectionSPI qosConnectionSPI = new QoSConnectionSPI();
		qosConnectionSPI.startServer();
	}

}
